package com.yingxin.yx.framework.commons.helper.loop;


import com.yingxin.yx.framework.commons.helper.DecimalHelper;
import com.yingxin.yx.framework.commons.helper.loop.setter.LoopBigDecimalSetter;

import java.math.BigDecimal;
import java.util.List;
import java.util.function.Function;

public class LoopSubtractHelper {

    /**
     * 循环扣减
     *
     * @param list        要扣减的列表
     * @param totalVal    要扣减的总值
     * @param function    每个item可以扣减的值
     * @param itemDispose 返回结构
     * @param <T>
     * @param <R>
     * @return
     */
    public static <T, R> BigDecimal apply(List<T> list, BigDecimal totalVal,
                                          Function<T, R> function,
                                          LoopBigDecimalSetter<T> itemDispose) {
        for (T t : list) {
            BigDecimal val = (BigDecimal) function.apply(t);
            BigDecimal min = totalVal.min(val);
            itemDispose.apply(t, min);
            totalVal = DecimalHelper.subtract(totalVal, min);
            if (totalVal.compareTo(BigDecimal.ZERO) <= 0) {
                break;
            }
        }
        return totalVal;
    }

}
